'''
Created on 07/04/2009

@author: Edward
'''

from yarra.datastore import dsconstants, dsofactory
from yarra.datastore.dso import DSO
from yarra.datastore.dsstub import DSStub
from yarra.datastore.dst import DST
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.handler import messagetypeconstants
from xml.etree import ElementTree
from yarra.logging import yarralogging
import httplib
import os

class PublicApplicationStatusWebServiceResponseHandler(BaseEventHandler):
    
    def get_sub_element_text(self, element, tag_name):
        sub_element = element.find(tag_name)
        if sub_element is not None:
            return sub_element.text
        else:
            return None
        
    def do(self, data):
        dso = data
                
        web_service_response_dst = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                predicate=dsconstants.PREDICATE_WEB_SERVICE_RESPONSE)
        web_service_response = web_service_response_dst.get_literal()

        message_request_node_dst = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_MESSAGE_REQUEST_NODE)        
        message_request_node = message_request_node_dst.get_literal()
        
        spear_reference_number_dst = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
                                 predicate=dsconstants.PREDICATE_SPEAR_REFERENCE_NUMBER)
        
        application = ElementTree.XML(web_service_response)

        client_name = None               
        property_address = None
        application_type = None
        permit_category_type = None
        council_name = None
        application_state = None
        documents = []
        cc_version = None
        
        response_code = application.find('.//{http://response.webservice.spear.lx.dse.vic.gov.au}code').text
        response_message = application.find('.//{http://response.webservice.spear.lx.dse.vic.gov.au}message').text
        if response_code == "000":        
            client_name = application.find('.//{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}clientName').text               
            property_address = application.find('.//{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}address').text
            application_type = application.find('.//{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}applicationType').text
            permit_category_type = application.find('.//{http://permitCategory.was6.webservice.spear.lx.dse.vic.gov.au}permitCategoryType').text
            council_name = application.find('.//{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}councilName').text
            application_state = application.find('.//{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}applicationState').text
            for document in application.findall('.//{http://application.response.webservice.spear.lx.dse.vic.gov.au}documentType'):
                if document.text is not None:
                    documents.append(str(document.text))
            cc_version = application.find('.//{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}ccVersion').text      

        request_id_dst = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                predicate=dsconstants.PREDICATE_REQUEST_ID)
        
        message_content_dst = DST(subject=dsconstants.SUBJECT_ROOT,
            predicate=dsconstants.PREDICATE_MESSAGE_CONTENT,
            object=dsconstants.SUBJECT_MESSAGE_CONTENT)

        response_code_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_RESPONSE_CODE,
            literal=response_code)

        response_message_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_RESPONSE_MESSAGE,
            literal=response_message)

        client_name_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_CLIENT_NAME,
            literal=client_name)

        property_address_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_PROPERTY_ADDRESS,
            literal=property_address)

        application_type_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_APPLICATION_TYPE,
            literal=application_type)

        permit_category_type_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_PERMIT_CATEGORY_TYPE,
            literal=permit_category_type)
                                                
        council_name_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_COUNCIL_NAME,
            literal=council_name)

        application_state_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_APPLICATION_STATE,
            literal=application_state)
        
        documents_dsts = []
        for document in documents:
            document_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
                predicate=dsconstants.PREDICATE_DOCUMENT,
                literal=document)
            documents_dsts.append(document_dst)
        
        cc_version_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_CC_VERSION,
            literal=cc_version)                        
        
        message_destination_node_dst = DST(subject=dsconstants.SUBJECT_ROOT,
            predicate=dsconstants.PREDICATE_MESSAGE_DESTINATION_NODE,
            literal=message_request_node)

        message_type_dst = DST(subject=dsconstants.SUBJECT_ROOT, 
            predicate=dsconstants.PREDICATE_MESSAGE_TYPE, 
            literal=messagetypeconstants.PUBLIC_APPLICATION_STATUS_TEST_RESPONSE_MESSAGE_TYPE)
                        
        new_dsts = [request_id_dst,
                message_content_dst,
                response_code_dst,
                response_message_dst,
                client_name_dst,
                property_address_dst,
                application_type_dst,
                permit_category_type_dst,
                council_name_dst,
                application_state_dst,
                cc_version_dst,
                message_destination_node_dst,
                message_type_dst,
                spear_reference_number_dst]
        new_dsts.extend(documents_dsts)
        
        new_dso = DSO(dsts=new_dsts)
        event = Event(eventconstants.SEND_TO_HUB_EVENT_TYPE, new_dso)
        EventManager().add_event(event)

class PublicApplicationStatusTestHTTPResponseHandler(BaseEventHandler):
    
    __logger = None
    
    def __init__(self):
        self.__logger = yarralogging.get_logger(DSStub().get_application_name())
        
    def do(self, data):
        dso = data
        request_id = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                                 predicate=dsconstants.PREDICATE_REQUEST_ID).get_literal()
        ds = DSStub()
        
        result = ds.get_outstanding_requests(int(request_id))
        if result:
            (http_request, lock) = result
        else:
            self.__logger.info('Cannot find message entry with request_id ' + request_id)
            return
      
        response_code = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_RESPONSE_CODE).get_literal()
        response_message = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_RESPONSE_MESSAGE).get_literal()
        client_name = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_CLIENT_NAME).get_literal()
        property_address = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_PROPERTY_ADDRESS).get_literal()
        application_type = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_APPLICATION_TYPE).get_literal()                                 
        permit_category_type = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_PERMIT_CATEGORY_TYPE).get_literal()
        council_name = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_COUNCIL_NAME).get_literal()
        application_state = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_APPLICATION_STATE).get_literal()
        document_dsts = dso.get_dsts(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_DOCUMENT)
        cc_version = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_CC_VERSION).get_literal()                                                                                                                                    
        spear_reference_number = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
                                         predicate=dsconstants.PREDICATE_SPEAR_REFERENCE_NUMBER).get_literal()                                 
        
        relative_path = None
        if response_code == "000":
            relative_path = "../../../pages/im/public-application-status-test-result.html"
        else:
            relative_path = "../../../pages/im/imerror.html"
        
        # get the html template
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = None
        if application_state:
            if document_dsts:
                document_list_html = "<ul>"
                for document_dst in document_dsts:
                    document_list_html += "<li>" + str(document_dst.get_literal()) + "</li>"
                document_list_html += "</ul>"
            html_string = html_template_string.replace('${spear_reference_number}', spear_reference_number) \
                                                .replace('${response_code}', response_code) \
                                                .replace('${response_message}', str(response_message)) \
                                                .replace('${client_name}', str(client_name)) \
                                                .replace('${property_address}', str(property_address)) \
                                                .replace('${application_type}', str(application_type)) \
                                                .replace('${permit_category_type}', str(permit_category_type)) \
                                                .replace('${council_name}', str(council_name)) \
                                                .replace('${application_state}', str(application_state)) \
                                                .replace('${documents}', document_list_html) \
                                                .replace('${cc_version}', str(cc_version))
                                                
        else:
            html_string = html_template_string.replace('${fault_message}', "unknown-spear-reference")
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)
        event = Event(eventconstants.HTTP_RESPONSE_EVENT_TYPE, new_dso)
        EventManager().add_event(event)    